#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Shopify 语言配置路由模块 (FastAPI版本)
提供用户语言配置的写入和发布API端点
"""

from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field
from typing import Optional

from app.conf.config import logger
from app.services.shopify_language_config_service import shopify_language_config_service
from app.utils.error_handling import BadRequestError, InternalServerError

# 创建FastAPI路由
router = APIRouter(
    prefix="/api/v1/shopify/language",
    tags=["shopify-language"]
)


# 请求模型定义
class WriteLanguageConfigRequest(BaseModel):
    """写入语言配置请求模型"""
    shopify_domain: str = Field(..., description="店铺域名", example="example.myshopify.com")
    target_language: str = Field(..., description="目标语言", example="zh-CN")


class PublishLanguageConfigRequest(BaseModel):
    """发布语言配置请求模型"""
    shopify_domain: str = Field(..., description="店铺域名", example="example.myshopify.com")
    target_language: str = Field(..., description="目标语言", example="zh-CN")


# 响应模型定义
class LanguageConfigResponse(BaseModel):
    """语言配置响应模型"""
    is_success: int = Field(..., description="操作是否成功")
    message: str = Field(..., description="操作消息")
    user_id: Optional[int] = Field(None, description="用户ID")
    shopify_domain: Optional[str] = Field(None, description="店铺域名")
    shop_default_language: Optional[str] = Field(None, description="店铺默认语言")
    target_language: Optional[str] = Field(None, description="目标语言")


class PublishConfigResponse(BaseModel):
    """发布配置响应模型"""
    is_success: int = Field(..., description="操作是否成功")
    message: str = Field(..., description="操作消息")
    user_id: Optional[int] = Field(None, description="用户ID")
    shopify_domain: Optional[str] = Field(None, description="店铺域名")


@router.post("/config", response_model=LanguageConfigResponse, status_code=status.HTTP_200_OK)
async def write_language_config(request_data: WriteLanguageConfigRequest):
    """
    写入用户语言配置
    
    - **shopify_domain**: 店铺域名
    - **target_language**: 目标语言
    """
    try:
        # 调用服务层写入配置
        result = shopify_language_config_service.write_language_config(
            request_data.shopify_domain, 
            request_data.target_language
        )
        
        return result
        
    except BadRequestError as e:
        logger.error(f"写入语言配置失败 - 参数错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail={
                'is_success': 0,
                'error': str(e)
            }
        )
    except InternalServerError as e:
        logger.error(f"写入语言配置失败 - 服务器错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                'is_success': 0,
                'error': str(e)
            }
        )
    except Exception as e:
        logger.error(f"写入语言配置失败 - 未知错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                'is_success': 0,
                'error': f'未知错误: {str(e)}'
            }
        )


@router.post("/publish", response_model=PublishConfigResponse, status_code=status.HTTP_200_OK)
async def publish_language_config(request_data: PublishLanguageConfigRequest):
    """
    发布用户语言配置
    
    - **shopify_domain**: 店铺域名
    - **target_language**: 目标语言
    """
    try:
        # 调用服务层发布配置
        result = shopify_language_config_service.publish_language_config(
            request_data.shopify_domain,
            request_data.target_language
        )
        
        return result
        
    except BadRequestError as e:
        logger.error(f"发布语言配置失败 - 参数错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail={
                'is_success': 0,
                'error': str(e)
            }
        )
    except InternalServerError as e:
        logger.error(f"发布语言配置失败 - 服务器错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                'is_success': 0,
                'error': str(e)
            }
        )
    except Exception as e:
        logger.error(f"发布语言配置失败 - 未知错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                'is_success': 0,
                'error': f'未知错误: {str(e)}'
            }
        )